//
//  LoginSafeTableViewController.m
//  bitcoin
//
//  Created by caiyajun on 2018/5/22.
//  Copyright © 2018年 比特币. All rights reserved.
//

#import "LoginSafeTableViewController.h"
#import "LCGrayButton.h"
#import "MainTabBarController.h"
#import "RecordTableViewController.h"
#import "LoginController.h"
@interface LoginSafeTableViewController ()
@property (weak, nonatomic) IBOutlet UILabel *emailLabel;

@property (weak, nonatomic) IBOutlet UITextField *emailMessageTF;
@property (weak, nonatomic) IBOutlet UITextField *geogleMessageTF;

@property (weak, nonatomic) IBOutlet UIButton *sureButton;
@property (weak, nonatomic) IBOutlet LCGrayButton *emailCodeBtn;
@end

@implementation LoginSafeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.navigationItem.leftBarButtonItem = back;
    
//    self.emailLabel.text=[UserDefaults objectForKey:K_EMAIL];
    
    
    [_emailMessageTF setValue:[UIColor colorWithHexString:@"#616372"] forKeyPath:@"_placeholderLabel.textColor"];
    [_geogleMessageTF setValue:[UIColor colorWithHexString:@"#616372"] forKeyPath:@"_placeholderLabel.textColor"];
    
    if ([self.pushType isEqualToString:@"forgetPassword"]) {
        self.emailLabel.text=self.u_email;
    }else{
        self.emailLabel.text=[NSString stringWithFormat:@"%@",[UserDefaults objectForKey:K_EMAIL]];
    }
    
//    if ([[UserDefaults objectForKey:K_ISEMAIL] isEqualToString:@"1"]) {
//        self.emailCodeBtn.hidden=NO;
//    }else{
//        self.emailCodeBtn.hidden=YES;
//    }
    [self.emailCodeBtn addTarget: self action:@selector(startTime:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.sureButton setBackgroundImage:[UIImage imageWithColor:RGBColor(86, 54, 157)] forState:(UIControlStateHighlighted)];
}

- (void)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)startTime:(UIButton *)sender{
    
    DebugLog(@"我点击了.... ");
    [self changeShow];
    //emailCertifyVC   关闭邮箱验证
    //login   二次登陆安全验证
    //drawMoneyVC  提币安全验证
    //googleCertifyVC 关闭谷歌验证
    
    NSDictionary *param = @{@"accept_device" : self.emailLabel.text,
                            @"site" : @"10"
                            };
    [LSRequestManager postRequestWithURL:HUOBI(@"api/auth/sendYzm")
                                  params:param
                                 success:^(NSDictionary *responseData) {
                                     if ([responseData[@"ret"] integerValue ] == 0) {
                                         [MBProgressHUD showError:responseData[@"msg"]];
                                     } else {
                                         [MBProgressHUD showError:responseData[@"msg"]];
                                     }
                                 }
                                 failure:^(NSError *error) {
                                     
                                 }
                                 showHUD:NO];
    
    
    
    
    
    
    
    
    
    
    
    
}
-(void)changeShow{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.emailCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                self.emailCodeBtn.enabled = YES;
                
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.emailCodeBtn setTitle:[NSString stringWithFormat:@"重新获取%@秒",strTime] forState:UIControlStateNormal];
                self.emailCodeBtn.enabled = NO;
                
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0||indexPath.row==1) {
        if ([self.pushType isEqualToString:@"forgetPassword"]){
            if ([self.isSame isEqualToString:@"2"]&&[self.email isEqualToString:@"1"]) {
                return 51;
            }else{
                return 0;
            }
        }else{
            if ([[UserDefaults objectForKey:K_ISEMAIL] isEqualToString:@"1"]) {
                return 51;
            }else{
                return 0;
            }
        }
        
        
        
        
        
    }else if (indexPath.row==2){
        if ([self.pushType isEqualToString:@"forgetPassword"]){
            if ([self.google isEqualToString:@"1"]) {
                return 51;
            }else{
                return 0;
            }
        }else{
            if ([[UserDefaults objectForKey:K_ISGOOGLE] isEqualToString:@"1"]) {
                return 51;
            }else{
                return 0;
            }
        }
        
    }
    return 51;
    
}

- (IBAction)sureAction {
    //认证判断
    [self.view endEditing:YES];
    if ([self.pushType isEqualToString:@"forgetPassword"]){
        if ([self.isSame isEqualToString:@"2"]&&[self.email isEqualToString:@"1"]) {
            if (self.emailMessageTF.text.length==0) {
                [MBProgressHUD showError:@"请输入验证码"];
                return;
            }
        }
        
    }else{
        if ([[UserDefaults objectForKey:K_ISEMAIL]isEqualToString:@"1"]){
            if (self.emailMessageTF.text.length==0) {
                [MBProgressHUD showError:@"请输入验证码"];
                return;
            }
        }
    }
    
    
    if ([self.pushType isEqualToString:@"forgetPassword"]){
        if ([self.google isEqualToString:@"1"]) {
            if (self.geogleMessageTF.text.length==0) {
                [MBProgressHUD showError:@"请输入请输谷歌验证码"];
                return;
            }
        }
    }else{
        if ([[UserDefaults objectForKey:K_ISGOOGLE]isEqualToString:@"1"]){
            if (self.geogleMessageTF.text.length==0) {
                [MBProgressHUD showError:@"请输入请输谷歌验证码"];
                return;
            }
        }
    }
         
    
        
    if ([self.pushType isEqualToString:@"login"]) {
        NSDictionary *param= @{@"login_val" : self.emailLabel.text?self.emailLabel.text:@"",
                               @"yzm" : self.emailMessageTF.text?self.emailMessageTF.text:@"",
                               @"reg_type" :@"2",
                               @"google_code" : self.geogleMessageTF.text?self.geogleMessageTF.text:@"",
                               };
        [LSRequestManager postRequestWithURL:HUOBI(@"api/auth/loginCheck")
                                      params:param
                                     success:^(NSDictionary *responseData) {
                                         if ([responseData[@"ret"] integerValue ] == 0) {
                                             [UserDefaults setObject:responseData[@"data"][@"token"] forKey:K_LOGININFO_TOKEN];
                                             [UserDefaults synchronize];
                                             
                                             
                                             
                                             
                                             UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
                                             MainTabBarController *mainView = [[MainTabBarController alloc] init];
                                             window.rootViewController = mainView;
                                         } else {
                                             [MBProgressHUD showError:responseData[@"msg"]];
                                         }
                                     }
                                     failure:^(NSError *error) {
                                         
                                     }
                                     showHUD:NO];
    }else if ([self.pushType isEqualToString:@"emailCertifyVC"]||[self.pushType isEqualToString:@"googleCertifyVC"]||[self.pushType isEqualToString:@"forgetPassword"]){
        NSDictionary *param= @{@"email" : self.emailLabel.text?self.emailLabel.text:@"",
                               @"email_code" : self.emailMessageTF.text?self.emailMessageTF.text:@"",
                               @"app" :@"1",
                               @"google" : self.geogleMessageTF.text?self.geogleMessageTF.text:@"",
                               };
        [LSRequestManager getRequestWithURL:HUOBI(@"api/auth/securityVerify")
                                      params:param
                                     success:^(NSDictionary *responseData) {
                                         if ([responseData[@"ret"] integerValue ] == 0) {
                                             if ([self.pushType isEqualToString:@"forgetPassword"]) {
                                                 
                                                 
                                                 [self changeLoginPassword];
                                                 
                                                 
                                                 
                                             }else{
                                                 [self changeStatus];
                                             }
                                             
                                             
                                             
                                             
                                         } else {
                                             [MBProgressHUD showError:responseData[@"msg"]];
                                         }
                                     }
                                     failure:^(NSError *error) {
                                         
                                     }
                                     showHUD:NO];
    }else if ([self.pushType isEqualToString:@"drawMoneyVC"]){
        NSDictionary *param= @{@"currency_id" : self.currency_id,
                               @"amount" : self.amount,
                               @"address" :self.address,
                               @"email" : self.emailLabel.text?self.emailLabel.text:@"",
                               @"email_code" : self.emailMessageTF.text?self.emailMessageTF.text:@"",
                               @"google" : self.geogleMessageTF.text?self.geogleMessageTF.text:@"",
                               };
        [LSRequestManager postRequestWithURL:HUOBI(@"api/withdraw/drawMoney")
                                      params:param
                                     success:^(NSDictionary *responseData) {
                                         if ([responseData[@"ret"] integerValue ] == 0) {
                                             [MBProgressHUD showError:responseData[@"msg"]];
                                             
                                             for (UIViewController *controller in self.navigationController.viewControllers) {
                                                 if ([controller isKindOfClass:[RecordTableViewController class]]) {
                                                     [self.navigationController popToViewController:controller animated:YES];
                                                     
                                                 }
                                                 
                                             }
                                             
                                             
                                             
                                             
                                         } else {
                                             [MBProgressHUD showError:responseData[@"msg"]];
                                         }
                                     }
                                     failure:^(NSError *error) {
                                         
                                     }
                                     showHUD:NO];
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
-(void)changeLoginPassword{
    NSDictionary *param = @{@"login_val" : self.forgetEmail,
                            @"reg_type" : @"2",
                            @"yzm" : self.forgetEmailSafe,
                            @"new_login_pwd" : self.forgetNewPassword
                            };
    [LSRequestManager putRequestWithURL:HUOBI(@"api/auth/resetPwd")
                                 params:param
                                success:^(NSDictionary *responseData) {
                                    if ([responseData[@"ret"] integerValue ] == 0) {
                                        
                                        for (UIViewController *controller in self.navigationController.viewControllers) {
                                            if ([controller isKindOfClass:[LoginController  class]]) {
                                                [self.navigationController popToViewController:controller animated:YES];
                                                
                                            }
                                            
                                        }
                                        
                                        

                                        
                                        
                                        
                                    } else {
                                        [MBProgressHUD showError:responseData[@"msg"]];
                                    }
                                }
                                failure:^(NSError *error) {
                                    
                                }
                                showHUD:NO];
    
    
    
}
-(void)changeStatus{
    NSString*type;
    if ([self.pushType isEqualToString:@"emailCertifyVC"]){
        type=@"2";
    }else if ([self.pushType isEqualToString:@"googleCertifyVC"]){
        type=@"3";
    }
    NSDictionary *param= @{@"type" : type,
                           @"on" : @"0"};
    [LSRequestManager putRequestWithURL:HUOBI(@"api/user/setSecrityMethod")
                                 params:param
                                success:^(NSDictionary *responseData) {
                                    if ([responseData[@"ret"] integerValue ] == 0) {
                                        if ([self.pushType isEqualToString:@"emailCertifyVC"]) {
                                            [UserDefaults removeObjectForKey:K_ISEMAIL];
                                            [UserDefaults removeObjectForKey:K_EMAIL];
                                            [UserDefaults synchronize];
                                            [[NSNotificationCenter defaultCenter] postNotificationName:@"closeEmailSafeNoti" object:nil];
                                        }else if ([self.pushType isEqualToString:@"googleCertifyVC"]){
                                            [UserDefaults removeObjectForKey:K_ISGOOGLE];
                                            [UserDefaults synchronize];
                                            [[NSNotificationCenter defaultCenter] postNotificationName:@"closeGoogleSafeNoti" object:nil];
                                        }
                                        
                                        
                                        [self.navigationController popViewControllerAnimated:YES];
                                        
                                        
                                        
                                        
                                        
                                        
                                        
                                    } else {
                                        [MBProgressHUD showError:responseData[@"msg"]];
                                    }
                                }
                                failure:^(NSError *error) {
                                    
                                }
                                showHUD:NO];
}
@end
